package com.computer.network.security.handler;

import com.alibaba.fastjson.JSON;
import com.computer.network.util.Result;
import com.computer.network.util.ResultCode;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * 认证用户无权限处理器
 *
 * @Author cgs
 * @Date 2022/8/19 11:35
 */
@Component
public class CustomerAccessDeniedHandler implements AccessDeniedHandler {
    @Resource
    Result result;
    @Resource
    ResultCode resultCode;

    @Override
    public void handle(HttpServletRequest httpServletRequest,
                       HttpServletResponse httpServletResponse,
                       AccessDeniedException e)
            throws IOException, ServletException {
        //设置编码格式
        httpServletResponse.setContentType("application/json;charset=utf-8");
        //获取输出流对象
        ServletOutputStream outputStream = httpServletResponse.getOutputStream();
        Result error = result.error(resultCode.NO_AUTH, "您无权限操作，请联系管理员进行修改");
        //转换成json格式
        String result = JSON.toJSONString(error);
        //输出流
        outputStream.write(result.getBytes(StandardCharsets.UTF_8));
        //清空缓存区
        outputStream.flush();
        //关闭缓存
        outputStream.close();
    }
}
